<template>
  <div class="container">
    <Breadcrumb :items="['站点管理', '充电桩列表']" />
    <a-card class="general-card" title="充电桩列表">
      <!-- 统计卡片 -->
      <a-row :gutter="16" class="statistics-row">
        <a-col :span="8">
          <a-card class="statistics-card">
            <div class="statistics-content">
              <div class="statistics-title">总数量</div>
              <div class="statistics-value">{{ statistics.total }}</div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card class="statistics-card">
            <div class="statistics-content">
              <div class="statistics-title">在线数量</div>
              <div class="statistics-value" style="color: #00b42a">{{
                statistics.online
                }}</div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card class="statistics-card">
            <div class="statistics-content">
              <div class="statistics-title">离线数量</div>
              <div class="statistics-value" style="color: #f53f3f">{{
                statistics.offline
                }}</div>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <a-row>
        <a-col :flex="1">
          <a-form :model="searchForm" label-align="left" :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }" label-layout="inline">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="name" :label="$t('充电桩名称')">
                  <a-input v-model="searchForm.name" :placeholder="$t('请输入充电桩名称')" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="code" :label="$t('充电桩编号')">
                  <a-input v-model="searchForm.code" :placeholder="$t('请输入充电桩编号')" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="chargingType" :label="$t('充电类型')">
                  <a-select v-model="searchForm.chargingType" :placeholder="$t('请选择充电类型')" allow-clear>
                    <a-option v-for="type in chargingTypeList" :key="type.id" :value="type.id" :label="type.name">
                      {{ type.name }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select v-model="searchForm.status" :placeholder="$t('请选择状态')" allow-clear>
                    <a-option :value="1">{{ $t('在线') }}</a-option>
                    <a-option :value="0">{{ $t('离线') }}</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="chargingGroupId" :label="$t('所属站点')">
                  <a-select v-model="searchForm.chargingGroupId" :placeholder="$t('请选择站点')" allow-clear
                    :loading="stationLoading" @change="onStationChange" allow-search filter-option>
                    <a-option v-for="station in stationList" :key="station.id" :value="station.id"
                      :label="station.name">
                      {{ station.name }}
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-button type="primary" @click="openAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            {{ $t('新增') }}
          </a-button>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <!-- 充电桩列表 -->
      <a-table :loading="loading" :data="pileList" :pagination="pagination" @page-change="onPageChange"
        @page-size-change="onPageSizeChange" stripe>
        <template #columns>
          <a-table-column title="序号" :width="80" align="center">
            <template #cell="{ rowIndex }">
              {{
                (pagination.current - 1) * pagination.pageSize + rowIndex + 1
              }}
            </template>
          </a-table-column>
          <a-table-column title="充电桩名称" data-index="name" :width="160" />
          <a-table-column title="充电桩编号" data-index="code" :width="150" />
          <a-table-column title="所属站点" :width="150">
            <template #cell="{ record }">
              {{ record.chargingGroupName || '-' }}
            </template>
          </a-table-column>
          <a-table-column title="状态" :width="100">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'" size="medium">
                {{ record.status === 1 ? '在线' : '离线' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="枪口数量" data-index="socketCount" :width="120" />
          <a-table-column title="充电类型" data-index="chargingTypeName" :width="120" />
          <a-table-column title="创建时间" :width="180">
            <template #cell="{ record }">
              {{ formatTime(record.createDate) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="300" fixed="right" align="center">
            <template #cell="{ record }">
              <a-space>
                <!-- <a-button type="text" size="small" @click="viewDetail(record)">
                  <template #icon><icon-eye /></template>
    详情
    </a-button> -->
                <a-button type="text" size="small" @click="openEditDialog(record)">
                  <template #icon><icon-edit /></template>
                  编辑
                </a-button>
                <!-- <a-button type="text" size="small" @click="viewGuns(record)">
                  <template #icon><icon-settings /></template>
                  管理充电枪
                </a-button> -->
                <a-button type="text" size="small" @click="handleRestart(record)">
                  <template #icon><icon-refresh /></template>
                  重启
                </a-button>
                <a-button type="text" size="small" @click="handleTiming(record)">
                  <template #icon><icon-clock-circle /></template>
                  对时
                </a-button>
                <a-button type="text" status="danger" size="small" @click="handleDelete(record)">
                  <template #icon><icon-delete /></template>
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑充电桩对话框 -->
    <a-modal v-model:visible="dialogVisible" :title="isEdit ? '编辑充电桩' : '新增充电桩'" :mask-closable="false"
      :unmount-on-close="false" width="600px" :footer="false" class="pile-modal">
      <a-form ref="formRef" :model="form" :rules="rules" label-align="left" :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }" class="pile-form">
        <a-form-item field="name" label="充电桩名称" required>
          <a-input v-model="form.name" placeholder="请输入充电桩名称" />
        </a-form-item>
        <a-form-item field="code" label="充电桩编号" required>
          <a-input v-model="form.code" placeholder="请输入充电桩编号" />
        </a-form-item>
        <a-form-item field="chargingGroupId" label="所属站点" required>
          <a-select v-model="form.chargingGroupId" placeholder="请选择站点" :loading="stationLoading" allow-search
            filter-option @change="onHandleStationChange" :label="getStationNameById(form.chargingGroupId)">
            <a-option v-for="station in stationList" :key="station.id" :value="station.id" :label="station.name">
              {{ station.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="chargingType" label="充电类型" required>
          <a-select v-model="form.chargingType" placeholder="请选择充电类型" :loading="chargingTypeLoading">
            <a-option v-for="type in chargingTypeList" :key="type.chargingType" :value="type.chargingType"
              :label="type.name">
              {{ type.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="socketCount" label="枪口数量" required>
          <a-input-number v-model="form.socketCount" placeholder="请输入枪口数量" :min="1" :max="10" />
        </a-form-item>
        <!-- <a-form-item field="manufacturer" label="设备厂商">
          <a-input v-model="form.manufacturer" placeholder="请输入设备厂商" />
        </a-form-item>
        <a-form-item field="model" label="设备型号">
          <a-input v-model="form.model" placeholder="请输入设备型号" />
        </a-form-item>
        <a-form-item field="remark" label="设备描述">
          <a-textarea v-model="form.remark" placeholder="请输入设备描述" />
        </a-form-item> -->

        <a-divider>第三方平台关联（可选）</a-divider>

        <div v-for="(relation, index) in form.serverRelations" :key="index" class="server-relation-item">
          <div class="relation-header">
            <span class="relation-title">第三方平台关联 #{{ index + 1 }}</span>
            <div class="relation-actions">
              <span :style="{
                color: relation.enabled === 0 ? '#f53f3f' : '#00b42a',
                marginRight: '8px',
                fontWeight: 500
              }">{{ relation.enabled === 0 ? '禁用' : '启用' }}</span>
              <a-switch :model-value="relation.enabled === 1"
                @update:model-value="(val) => relation.enabled = val ? 1 : 0" size="small" />
              <a-divider direction="vertical" margin="0" />
              <a-button type="text" status="danger" size="mini" @click="removeServerRelation(index)">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </div>
          </div>

          <a-form-item :field="`serverRelations[${index}].forwardPileCode`" label="转发设备编号" required>
            <a-input v-model="relation.forwardPileCode" placeholder="请输入转发设备编号" />
          </a-form-item>

          <a-form-item :field="`serverRelations[${index}].serverId`" label="转发服务器" required>
            <a-select v-model="relation.serverId" placeholder="请选择转发平台" :loading="serverLoading" allow-search
              filter-option>
              <a-option v-for="server in serverList" :key="server.id" :value="server.id">
                <!-- {{ server.serverName }} ({{ server.serverIp }}:{{
                  server.serverPort
                }}) -->
                {{ server.serverName }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item :field="`serverRelations[${index}].isPrimary`" label="是否主服务器">
            <a-radio-group v-model="relation.isPrimary" type="button">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-divider v-if="index < form.serverRelations.length - 1" />
        </div>

        <div v-if="form.redirectPlatformLimit > form.serverRelations.length" class="add-relation-button">
          <a-button type="dashed" long @click="addServerRelation">
            <template #icon><icon-plus /></template>
            添加平台关联
          </a-button>
        </div>

        <div class="form-footer">
          <a-space>
            <a-button @click="dialogVisible = false">取消</a-button>
            <a-button type="primary" @click="handleSubmit">提交</a-button>
          </a-space>
        </div>
      </a-form>
    </a-modal>

    <!-- 充电桩详情对话框 -->
    <a-modal v-model:visible="detailVisible" title="充电桩详情" @cancel="detailVisible = false" :footer="false"
      width="700px">
      <div v-if="currentPile" class="pile-detail">
        <a-descriptions :column="2" bordered size="large">
          <a-descriptions-item label="充电桩名称">{{
            currentPile.name
            }}</a-descriptions-item>
          <a-descriptions-item label="充电桩编号">{{
            currentPile.code
            }}</a-descriptions-item>
          <a-descriptions-item label="充电类型">{{
            getChargingTypeName(currentPile.chargingType)
            }}</a-descriptions-item>
          <a-descriptions-item label="设备状态">
            <a-tag :color="currentPile.status === 1 ? 'green' : 'red'">
              {{ currentPile.status === 1 ? '在线' : '离线' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="枪口数量">{{
            currentPile.socketCount
            }}</a-descriptions-item>
          <a-descriptions-item label="所属站点">{{
            currentPile.carStationName || '-'
            }}</a-descriptions-item>
          <a-descriptions-item label="IP地址">{{
            currentPile.ipAddress || '未设置'
            }}</a-descriptions-item>
          <a-descriptions-item label="设备型号">{{
            currentPile.model || '未知'
            }}</a-descriptions-item>
          <a-descriptions-item label="最后活动时间">{{
            formatTime(currentPile.updateTime)
            }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{
            formatTime(currentPile.createTime)
            }}</a-descriptions-item>
          <a-descriptions-item label="设备描述" :span="2">{{
            currentPile.remark || '无'
            }}</a-descriptions-item>
        </a-descriptions>

        <div class="detail-footer">
          <a-button type="primary" @click="detailVisible = false">关闭</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal, Result } from '@arco-design/web-vue';
import { useRouter } from 'vue-router';
import useLoading from '@/hooks/loading';
import axios from 'axios';
import type { FormInstance } from '@arco-design/web-vue';
import { getChargingTypeList } from '@/api/charging-type';
import type { ChargingType as ChargingTypeModel } from '@/api/charging-type';
import { updatePileEnabled } from '@/api/charging-pile';
import {
  IconThunderbolt,
  IconBulb,
  IconEye,
  IconEdit,
  IconSettings,
  IconDelete,
  IconSync,
  IconRefresh,
  IconClockCircle,
  IconSearch,
  IconPlus,
  IconArrowLeft,
} from '@arco-design/web-vue/es/icon';

// 充电桩数据接口
interface ChargingPile {
  id: number;
  createTime: string;
  updateTime: string;
  code: string;
  name: string;
  chargingGroupId: number;
  chargingType: number;
  power: number;
  voltage: number;
  current: number;
  manufacturer: string;
  model: string;
  productionDate: string;
  installationDate: string;
  lastMaintenanceDate: string;
  nextMaintenanceDate: string;
  socketCount: number;
  protocolType: string;
  ipAddress: string;
  port: number;
  locationDesc: string;
  longitude: number;
  latitude: number;
  status: number;
  enabled: number;
  switchLoading?: boolean;
  isDeleted: number;
  sortOrder: number;
  createBy: string;
  updateBy: string;
  remark: string;
  carStationName: string;
  redirectPlatformLimit: number;
}

// 充电类型接口
interface ChargingType {
  id: number;
  typeName: string;
  typeCode: string;
  remark: string;
  createTime: string;
  updateTime: string;
  chargingType: number;
}

// 站点数据接口
interface Station {
  id: number;
  name: string;
  address: string;
  status: number;
  redirectPlatformLimit: number;
}

// 服务器接口
interface ForwardServer {
  id: number;
  serverName: string;
  serverIp: string;
  serverPort: number;
  serverType: number;
  status: number;
  remark: string;
}

// 路由
const router = useRouter();

// 加载状态
const { loading, setLoading } = useLoading();
const stationLoading = ref(false);
const serverLoading = ref(false);
const chargingTypeLoading = ref(false);

// 对话框状态
const dialogVisible = ref(false);
const detailVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance | null>(null);
const currentPile = ref<ChargingPile | null>(null);

// 充电桩列表
const pileList = ref<ChargingPile[]>([]);
const stationList = ref<Station[]>([]);
const serverList = ref<ForwardServer[]>([]);
const chargingTypeList = ref<ChargingTypeModel[]>([]);

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  chargingType: undefined as number | undefined,
  status: undefined as number | undefined,
  chargingGroupId: undefined as number | undefined,
});

// 分页
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 20,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});
// 服务器关联数据
interface ServerRelationItem {
  serverId: number | undefined;
  forwardPileCode: string;
  isPrimary: number;
  enabled: number;
}
// 表单数据
interface FormState {
  id?: number;
  name: string;
  code: string;
  chargingType: number;
  locationDesc: string;
  ipAddress: string;
  manufacturer: string;
  model: string;
  status: number;
  remark: string;
  chargingGroupId: number | undefined;
  power: number;
  voltage: number;
  current: number;
  protocolType: string;
  port: number;
  longitude: number;
  latitude: number;
  socketCount: number;
  redirectPlatformLimit: number;
  serverRelations: ServerRelationItem[];
}

const formInitialState: FormState = {
  name: '',
  code: '',
  chargingType: 0,
  locationDesc: '',
  ipAddress: '',
  manufacturer: '',
  model: '',
  status: 0,
  remark: '',
  chargingGroupId: undefined,
  power: 0,
  voltage: 0,
  current: 0,
  protocolType: '',
  port: 0,
  longitude: 0,
  latitude: 0,
  socketCount: 1,
  redirectPlatformLimit: 0,
  serverRelations: [],
};

const form = reactive<FormState>({ ...formInitialState });

// 表单验证规则
const rules = {
  pileName: [{ required: true, message: '请输入充电桩名称' }],
  pileCode: [{ required: true, message: '请输入充电桩编号' }],
  pileType: [{ required: true, message: '请选择充电类型' }],
  gunCount: [{ required: true, message: '请输入枪口数量' }],
  stationId: [{ required: true, message: '请选择所属站点' }],
  // 服务器关联 - 后面会根据需要决定是否必填
};

// 获取充电桩类型文本
function getDeviceTypeText(type: number) {
  switch (type) {
    case 1:
      return '直流快充';
    case 2:
      return '交流慢充';
    case 3:
      return '超级快充';
    default:
      return '未知类型';
  }
}

// 格式化时间
function formatTime(time?: number | string | null) {
  if (!time) return '-';
  try {
    const date = new Date(typeof time === 'string' ? time : Number(time));
    if (Number.isNaN(date.getTime())) return '-';
    return date
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      })
      .replace(/\//g, '-');
  } catch (error) {
    return '-';
  }
}

// 获取充电桩列表数据
async function fetchData() {
  setLoading(true);
  try {
    const params = {
      current: pagination.current,
      size: pagination.pageSize,
      name: searchForm.name || undefined,
      code: searchForm.code || undefined,
      chargingType: searchForm.chargingType,
      status: searchForm.status,
      chargingGroupId: searchForm.chargingGroupId,
    };

    const response = await axios.get('/api/charging/pile/page', { params });
    pileList.value = response.data.records;
    pagination.total = response.data.total;
    console.log('获取充电桩列表成功:', pileList.value);
  } catch (error) {
    console.error('获取充电桩列表失败:', error);
    Message.error('获取充电桩列表失败');
  } finally {
    setLoading(false);
  }
}

// 获取站点列表
async function fetchStationList() {
  stationLoading.value = true;
  try {
    const response = await axios.get('/api/v1/car/charging/group/queryAll');
    stationList.value = response.data;
  } catch (error) {
    console.error('获取站点列表失败:', error);
    Message.error('获取站点列表失败');
  } finally {
    stationLoading.value = false;
  }
}

// 获取转发服务器列表
async function fetchServerList() {
  serverLoading.value = true;
  try {
    const response = await axios.get('/api/forward/server/list');
    serverList.value = response.data;
  } catch (error) {
    console.error('获取转发服务器列表失败:', error);
    Message.error('获取转发服务器列表失败');
  } finally {
    serverLoading.value = false;
  }
}

// 获取充电类型列表
async function fetchChargingTypeList() {
  chargingTypeLoading.value = true;
  try {
    const res = await getChargingTypeList();
    if (res.code === 200) {
      chargingTypeList.value = res.data;
      console.log('chargingTypeList:', res.data);
    } else {
      Message.error(res.message || '获取充电类型列表失败');
    }
  } catch (error) {
    console.error('获取充电类型列表失败:', error);
    Message.error('获取充电类型列表失败');
  } finally {
    chargingTypeLoading.value = false;
  }
}

// 站点选择变化
function onStationChange(value: number | undefined) {
  console.log('站点选择变化:', value);
  searchForm.chargingGroupId = value;
}
function onHandleStationChange(value: number | undefined) {
  form.chargingGroupId = value;
  const station = stationList.value.find((s) => s.id === value);
  console.log('station:', station);
  if (station) {
    form.redirectPlatformLimit = station.redirectPlatformLimit;
  }
  console.log('form:', form);
  console.log('站点选择变化:', value);
}

// 搜索
function search() {
  fetchData();
  fetchStatistics();
}

// 重置搜索条件
function reset() {
  searchForm.name = '';
  searchForm.code = '';
  searchForm.chargingType = undefined;
  searchForm.status = undefined;
  searchForm.chargingGroupId = undefined;
  pagination.current = 1;
  fetchData();
  fetchStatistics();
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

// 打开新增对话框
function openAddDialog() {
  isEdit.value = false;
  Object.assign(form, {
    ...formInitialState,
    id: undefined, // 确保新增时id为undefined
  });
  dialogVisible.value = true;
}

// 打开编辑对话框
async function openEditDialog(pile: ChargingPile) {
  console.log('openEditDialog:', pile);
  isEdit.value = true;
  Object.assign(form, {
    id: pile.id,
    name: pile.name,
    code: pile.code,
    chargingType: pile.chargingType,
    locationDesc: pile.locationDesc,
    ipAddress: pile.ipAddress || '',
    manufacturer: pile.manufacturer || '',
    model: pile.model || '',
    status: pile.status,
    remark: pile.remark || '',
    chargingGroupId: pile.chargingGroupId,
    power: pile.power,
    voltage: pile.voltage,
    current: pile.current,
    protocolType: pile.protocolType,
    port: pile.port,
    longitude: pile.longitude,
    latitude: pile.latitude,
    socketCount: pile.socketCount,
    redirectPlatformLimit: pile.redirectPlatformLimit,
    // 清空服务器关联数据，等待加载
    serverRelations: [],
  });
  console.log('编辑参数form:', form);
  // 获取充电桩的服务器关联信息
  await fetchPileServerRelation(pile.id);

  dialogVisible.value = true;
}

// 获取充电桩的服务器关联信息
async function fetchPileServerRelation(pileId: number) {
  try {
    const params = {
      current: 1,
      pageSize: 10, // 获取更多关联关系
      pileId: pileId,
    };

    const response = await axios.get('/api/pile/server/relation/page', {
      params,
    });
    if (response.data.records && response.data.records.length > 0) {
      // 清空原有关联
      form.serverRelations = [];

      // 添加所有关联
      response.data.records.forEach((relation: any) => {
        form.serverRelations.push({
          serverId: relation.relation.serverId,
          forwardPileCode: relation.relation.forwardPileCode,
          isPrimary: relation.relation.isPrimary,
          enabled: relation.relation.enabled
        });
      });
    }
  } catch (error) {
    console.error('获取充电桩服务器关联失败:', error);
    // 不显示错误信息，保持表单为空
  }
}

// 查看充电桩详情
function viewDetail(pile: ChargingPile) {
  currentPile.value = pile;
  detailVisible.value = true;
}

// 查看充电枪
function viewGuns(pile: ChargingPile) {
  router.push({
    path: '/station/device/gun',
    query: {
      deviceId: pile.id,
      deviceName: pile.pileName,
      stationId: pile.stationId,
    },
  });
}

// 充电桩重启
async function handleRestart(pile: ChargingPile) {
  Modal.confirm({
    title: '确认重启',
    content: `确定要重启充电桩 "${pile.name}" 吗？`,
    onOk: async () => {
      try {
        const response = await axios.post('/api/charging/pile/restart', {
          code: pile.code,
        });

        if (response.code === 200) {
          Message.success('充电桩重启命令已发送');
        } else {
          Message.error(response.message || '充电桩重启失败');
        }
      } catch (error) {
        console.error('充电桩重启失败:', error);
        Message.error('充电桩重启失败');
      }
    },
  });
}

// 充电桩对时
async function handleTiming(pile: ChargingPile) {
  Modal.confirm({
    title: '确认对时',
    content: `确定要对充电桩 "${pile.name}" 进行时间同步吗？`,
    onOk: async () => {
      try {
        const response = await axios.post('/api/charging/pile/timing', {
          code: pile.code,
        });

        if (response.code === 200) {
          Message.success('充电桩对时命令已发送');
        } else {
          Message.error(response.message || '充电桩对时失败');
        }
      } catch (error) {
        console.error('充电桩对时失败:', error);
        Message.error('充电桩对时失败');
      }
    },
  });
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) {
    console.error('表单引用不存在');
    return;
  }

  try {
    // 表单验证
    await formRef.value.validate();

    setLoading(true);

    // 设置默认安装位置为空
    form.locationDesc = '';

    // 创建一个布尔值标记，表示是否需要创建服务器关联
    const needCreateRelation = form.serverRelations.length > 0;

    if (isEdit.value) {
      // 编辑充电桩
      try {
        const response = await axios.put(
          `/api/charging/pile/${form.id}`,
          form
        );
        if (response.code === 200) {
          // 如果需要创建服务器关联
          // if (needCreateRelation) {
          //   try {
          //     await createOrUpdateServerRelation(form.id as number);
          //   } catch (error) {
          //     console.error('创建服务器关联失败:', error);
          //     Message.warning('充电桩编辑成功，但服务器关联创建失败');
          //     dialogVisible.value = false;
          //     fetchData();
          //     return;
          //   }
          // }

          Message.success('编辑充电桩成功');
          dialogVisible.value = false;
          // 刷新列表
          fetchData();
        } else {
          Message.error(response.message || '编辑充电桩失败');
        }
      } catch (error) {
        console.error('编辑充电桩失败:', error);
        Message.error('编辑充电桩失败');
      }
    } else {
      // 新增充电桩
      try {
        const response = await axios.post('/api/charging/pile', form);

        if (response.code === 200) {
          // 如果需要创建服务器关联
          // if (needCreateRelation && response.data) {
          //   const newPileId = response.data.id || response.data;
          //   try {
          //     await createOrUpdateServerRelation(newPileId);
          //   } catch (error) {
          //     console.error('创建服务器关联失败:', error);
          //     Message.warning('充电桩创建成功，但服务器关联创建失败');
          //     dialogVisible.value = false;
          //     fetchData();
          //     return;
          //   }
          // }

          Message.success('新增充电桩成功');
          dialogVisible.value = false;
          // 刷新列表
          fetchData();
        } else {
          Message.error(response.message || '新增充电桩失败');
        }
      } catch (error) {
        console.error('新增充电桩失败:', error);
        Message.error('新增充电桩失败');
      }
    }
  } catch (errors) {
    console.error('表单验证失败:', errors);
  } finally {
    setLoading(false);
  }
};

// 创建或更新服务器关联
async function createOrUpdateServerRelation(pileId: number) {
  // 检查是否有必须字段未填
  for (const relation of form.serverRelations) {
    if (!relation.serverId || !relation.forwardPileCode) {
      throw new Error('服务器关联的服务器和转发设备编号不能为空');
    }
  }

  // 创建所有服务器关联
  const promises = form.serverRelations.map(async (relation) => {
    const params = {
      serverId: relation.serverId,
      isPrimary: relation.isPrimary,
      connectionStatus: 0, // 默认未连接
      pileId: pileId,
      forwardPileCode: relation.forwardPileCode,
    };

    // 使用自定义请求处理
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    const response = await fetch('/api/pile/server/relation', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(params),
    });

    const result = await response.json();

    if (result.code !== 200) {
      throw new Error(result.message || '创建服务器关联失败');
    }

    return result;
  });

  // 等待所有创建完成
  return Promise.all(promises);
}

// 删除充电桩
function handleDelete(pile: ChargingPile) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除充电桩 "${pile.name}" 吗？此操作不可恢复。`,
    onOk: async () => {
      setLoading(true);
      try {
        // 调用删除充电桩接口
        const response = await axios.delete(`/api/charging/pile/${pile.id}`);

        if (response.code === 200) {
          Message.success('删除充电桩成功');
          // 刷新列表
          fetchData();
        } else {
          Message.error(response.message || '删除充电桩失败');
        }
      } catch (error) {
        console.error('删除充电桩失败:', error);
        Message.error('删除充电桩失败');
      } finally {
        setLoading(false);
      }
    },
  });
}

// 根据站点ID获取站点名称
function getStationNameById(stationId?: number) {
  if (!stationId) return '';
  const station = stationList.value.find((s) => s.id === stationId);
  return station ? station.name : '';
}

// 添加服务器关联
function addServerRelation() {
  form.serverRelations.push({
    serverId: undefined,
    forwardPileCode: '',
    isPrimary: 0,
    enabled: 0  // 默认禁用
  });
}

// 移除服务器关联
function removeServerRelation(index: number) {
  form.serverRelations.splice(index, 1);
}

// 统计数据结构
interface Statistics {
  total: number;
  online: number;
  offline: number;
}

// 统计数据
const statistics = reactive<Statistics>({
  total: 0,
  online: 0,
  offline: 0,
});

// 获取统计数据
async function fetchStatistics() {
  try {
    const response = await axios.get('/api/charging/pile/statistics');
    if (response.code === 200) {
      Object.assign(statistics, response.data);
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    Message.error('获取统计数据失败');
  }
}

// 根据充电类型ID获取充电类型名称
function getChargingTypeName(chargingType?: number) {
  if (!chargingType) return '-';
  const type = chargingTypeList.value.find(
    (t) => t.chargingType === chargingType
  );
  return type ? type.name : '-';
}

// 处理启用状态变更
async function handleEnableChange(pile: ChargingPile, value: boolean) {
  // 设置loading状态
  pile.switchLoading = true;
  try {
    const res = await updatePileEnabled(pile.id, {
      enabled: value ? 1 : 0
    });

    if (res.code === 200) {
      Message.success(value ? '启用成功' : '禁用成功');
      // 更新本地数据
      pile.enabled = value ? 1 : 0;
    } else {
      Message.error(res.message || (value ? '启用失败' : '禁用失败'));
    }
  } catch (error) {
    console.error('更新启用状态失败:', error);
    Message.error('操作失败');
  } finally {
    pile.switchLoading = false;
  }
}

onMounted(() => {
  // 获取站点列表
  fetchStationList();
  // 获取服务器列表
  fetchServerList();
  // 获取充电桩列表
  fetchData();
  // 获取统计数据
  fetchStatistics();
  // 获取充电类型列表
  fetchChargingTypeList();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.pile-modal {
  :deep(.arco-modal-header) {
    border-bottom: 1px solid var(--color-border-2);
    padding: 16px 20px;

    .arco-modal-title {
      font-size: 18px;
      font-weight: 500;
    }
  }

  :deep(.arco-modal-body) {
    padding: 20px;
  }
}

.pile-form {
  .form-footer {
    display: flex;
    justify-content: center;
    margin-top: 24px;

    .arco-space {
      .arco-btn {
        min-width: 80px;
      }
    }
  }
}

.pile-detail {
  .detail-footer {
    margin-top: 24px;
    text-align: center;
  }
}

.server-relation-item {
  background-color: var(--color-fill-2);
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;

  .relation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .relation-title {
      font-weight: 500;
      font-size: 16px;
      color: var(--color-text-1);
    }

    .relation-actions {
      display: flex;
      align-items: center;
      gap: 8px;

      .arco-divider {
        height: 16px;
        margin: 0 8px;
      }
    }
  }
}

.add-relation-button {
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  .statistics-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px;

    .statistics-title {
      font-size: 14px;
      color: var(--color-text-3);
      margin-bottom: 8px;
    }

    .statistics-value {
      font-size: 24px;
      font-weight: 500;
      color: var(--color-text-1);
    }
  }
}
</style>
